package com.dindang.propertyfee.mvp.presenter;

import android.app.AlertDialog;
import android.app.Application;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.BatteryManager;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Toast;

import com.dindang.propertyfee.R;
import com.dindang.propertyfee.app.AppConst;
import com.dindang.propertyfee.app.utils.TextViewUtils;
import com.dindang.propertyfee.app.utils.print.AidlUtil;
import com.dindang.propertyfee.mvp.contract.PrintContract;
import com.dindang.propertyfee.mvp.model.entity.BaseResponse;
import com.dindang.propertyfee.mvp.model.entity.PropertyCharge;
import com.dindang.propertyfee.mvp.ui.adapter.custom.PaymentDetailViewAdapter;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.integration.AppManager;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.LogUtils;
import com.jess.arms.utils.RxLifecycleUtils;
import com.longxi.gamer_base.BaseAppConst;
import com.longxi.gamer_base.MyApplication;
import com.telpo.tps550.api.TelpoException;
import com.telpo.tps550.api.printer.ThermalPrinter;
import com.telpo.tps550.api.util.ShellUtils;
import com.telpo.tps550.api.util.StringUtil;
import com.telpo.tps550.api.util.SystemUtil;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import me.jessyan.rxerrorhandler.handler.RetryWithDelay;


@ActivityScope
public class PrintPresenter extends BasePresenter<PrintContract.Model, PrintContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    private PaymentDetailViewAdapter mAdapter;
    private List<PropertyCharge.RecordDetail> mRecordDetailList = new ArrayList<>();
    private boolean isDetailVisibility = true;
    private PropertyCharge.RecordDetailParam mParam = new PropertyCharge.RecordDetailParam();
    private PropertyCharge.RecordDetail mRecordDetail;

    private String[] mCollectionType = {"", "现金", "POS", "微信", "支付宝", "银行转账"};

    private String printVersion;
    private final int NOPAPER = 3;
    private final int LOWBATTERY = 4;
    private final int PRINTVERSION = 5;
    private final int PRINTBARCODE = 6;
    private final int PRINTQRCODE = 7;
    private final int PRINTPAPERWALK = 8;
    private final int PRINTCONTENT = 9;
    private final int CANCELPROMPT = 10;
    private final int PRINTERR = 11;
    private final int OVERHEAT = 12;
    private final int MAKER = 13;
    private final int PRINTPICTURE = 14;
    private final int NOBLACKBLOCK = 15;
    private final int PRINTSHORTCONTENT = 16;
    private final int PRINTLONGPICTURE = 17;
    private final int PRINTLONGTEXT = 18;
    private final int PRINTBLACK = 19;

    private int interval;
    private ProgressDialog progressDialog;
    private final static int MAX_LEFT_DISTANCE = 255;
    private boolean isCircle = false;

    final String PRT_TAG = "com.print.service.printservice";

    private String Result;
    private Boolean nopaper = false;
    private boolean LowBattery = false;

    String usbPrinterDev;

    MyHandler handler;
    private static int printerCheck = -1;
    private static int mPrinterType = -1;

    private static final int PRINTER_SY581 = 1;
    private static final int PRINTER_PT = 2;
    private static final int PRINTER_USB = 3;
    private static final int PRINTER_550_SERIAL = 4;
    private static final int PRINTER_550_USB = 5;

    private boolean haveUsbPrint = false;// 判断有无打印设备
    private StringBuffer content;
    private StringBuffer content1;
    ProgressDialog checkDialog;
    public void checkPrint() {
        checkDialog = new ProgressDialog(mRootView.getActivity());
        checkDialog.setTitle("检测打印机类型");
        checkDialog.setMessage(getString(R.string.watting));
        checkDialog.setCancelable(false);
        checkDialog.show();

        new Thread(new Runnable() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                printerCheck = SystemUtil.checkPrinter581();
                LogUtils.debugInfo(TAG, "printer check = " + printerCheck);
                if (printerCheck == 8) {
                    mPrinterType = PRINTER_SY581;
                } else if (printerCheck == 7 || printerCheck == 2) {
                    mPrinterType = PRINTER_PT;
                } else if (printerCheck == 0) {
                    mPrinterType = PRINTER_550_USB;
                } else if (printerCheck == 1) {
                    mPrinterType = PRINTER_550_SERIAL;
                }
                mRootView.getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        isDetailVisibility = false;
                        mAdapter.setIsDetailVisibility(isDetailVisibility);
                        mAdapter.notifyDataSetChanged();
                        setPrintUi();
                        checkDialog.dismiss();
                    }
                });
            }
        }).start();
    }

    public void onStart2() {
        IntentFilter pIntentFilter = new IntentFilter();
        pIntentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
        pIntentFilter.addAction("android.intent.action.BATTERY_CAPACITY_EVENT");
        mRootView.getActivity().registerReceiver(printReceive, pIntentFilter);
    }

    public void onStop() {
        if (progressDialog != null && !mRootView.getActivity().isFinishing()) {
            progressDialog.dismiss();
            progressDialog = null;
        }
        isCircle = false;

//        mRootView.getActivity().unregisterReceiver(printReceive);
        if(mRootView.getUsbThermalPrinter() != null && haveUsbPrint){
            mRootView.getUsbThermalPrinter().stop();
        }
    }

    private class MyHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case NOPAPER:
                    noPaperDlg();
                    break;
                case LOWBATTERY:
                    AlertDialog.Builder alertDialog = new AlertDialog.Builder(mRootView.getActivity());
                    alertDialog.setTitle(R.string.operation_result);
                    alertDialog.setMessage(getString(R.string.LowBattery));
                    alertDialog.setPositiveButton(getString(R.string.dialog_comfirm),
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {

                                }
                            });
                    alertDialog.show();
                    break;
                case NOBLACKBLOCK:
                    Toast.makeText(mRootView.getActivity(), R.string.maker_not_find, Toast.LENGTH_SHORT).show();
                    break;
                case PRINTVERSION:
                    if (msg.obj.equals("1")) {
                        haveUsbPrint = true;
                        mRootView.getTvCommit().setVisibility(View.VISIBLE);
                    } else {
                        haveUsbPrint = false;
//                        mRootView.getTvCommit().setVisibility(View.GONE);
                    }
                    break;
                case PRINTBARCODE:
//                    new barcodePrintThread().start();
                    break;
                case PRINTQRCODE:
//                    new qrcodePrintThread().start();
                    break;
                case PRINTPAPERWALK:
//                    new paperWalkPrintThread().start();
                    break;
                case PRINTCONTENT:
                    new contentPrintThread().start();

                    if(isCircle) {
                        handler.sendMessageDelayed(handler.obtainMessage(PRINTCONTENT), interval * 1000);
                    } else {
                        mRootView.getTvCommit().setEnabled(true);
                    }

                    break;
                case MAKER:
//                    new MakerThread().start();
                    break;
                case PRINTPICTURE:
//                    new printPicture().start();
                    break;
                case CANCELPROMPT:
                    if (progressDialog != null && !mRootView.getActivity().isFinishing()) {
                        progressDialog.dismiss();
                        progressDialog = null;
                    }
                    break;
                case OVERHEAT:
                    AlertDialog.Builder overHeatDialog = new AlertDialog.Builder(mRootView.getActivity());
                    overHeatDialog.setTitle(R.string.operation_result);
                    overHeatDialog.setMessage(getString(R.string.overTemp));
                    overHeatDialog.setPositiveButton(getString(R.string.dialog_comfirm),
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                }
                            });
                    overHeatDialog.show();
                    break;
                case PRINTSHORTCONTENT:
//                    new ShortTextPrintThread().start();
                    break;
                case PRINTLONGPICTURE:
//                    new printLongPicture().start();
                    break;
                case PRINTLONGTEXT:
//                    new printLongText().start();
                    break;
                case PRINTBLACK:
//                    new printBlackPicture().start();
                    break;
                default:
//                    Toast.makeText(mRootView.getActivity(), "Print Error!", Toast.LENGTH_LONG).show();
                    break;
            }
        }
    }

    private class contentPrintThread extends Thread {
        @Override
        public void run() {
            super.run();
            try {
                String temp = getUsbPrinterDev();
                LogUtils.debugInfo("idcard demo", "getUsbPrinterDev():"+temp);
                LogUtils.debugInfo("idcard demo", "preference:"+preference.getString("usbPrinterDev", "-1"));
                if(temp.equals("-2") || !temp.equals(preference.getString("usbPrinterDev", "-1"))){
                    mRootView.getUsbThermalPrinter().stop();
                    Thread.sleep(250);
                    mRootView.getUsbThermalPrinter().start(0);
                    getVersion();
                }

                for (PropertyCharge.RecordPrintStyle recordPrintStyle : mRecordPrintStyleList) {
                    mRootView.getUsbThermalPrinter().reset();
                    mRootView.getUsbThermalPrinter().setAlgin(recordPrintStyle.algin);
                    mRootView.getUsbThermalPrinter().setLeftIndent(recordPrintStyle.leftIndent);
                    mRootView.getUsbThermalPrinter().setLineSpace(recordPrintStyle.lineSpace);
                    mRootView.getUsbThermalPrinter().setBold(recordPrintStyle.isBold);
                    mRootView.getUsbThermalPrinter().setTextSize(recordPrintStyle.fontSize);
                    mRootView.getUsbThermalPrinter().setUnderline(recordPrintStyle.isUnderline);
                    mRootView.getUsbThermalPrinter().setGray(recordPrintStyle.printGray);
                    if(recordPrintStyle.content.contains(SEPARATOR)){
                        String[] sss = recordPrintStyle.content.split(SEPARATOR);
                        int TABLE_WIDTH = 384 / sss.length;// 每一个字段最多有多宽
                        StringBuffer stringBuffer = new StringBuffer();
                        for (String item : sss) {
                            int TEXT_WIDTH = mRootView.getUsbThermalPrinter().measureText(item);// 获取该文本的长度
                            int REMAINING_WIDTH = TABLE_WIDTH - TEXT_WIDTH;// 获取该文本在TABLE_WIDTH中还有多少剩余宽度
                            if(REMAINING_WIDTH >= 14){// 为什么要大于14呢 因为7是一个空格 这个方法是为了让文字居中
                                REMAINING_WIDTH = REMAINING_WIDTH / 2;
                                int SPACE = 0;
                                while (SPACE < REMAINING_WIDTH) {// 左边的空格
                                    stringBuffer.append(" ");
                                    SPACE+=7;
                                }
                                stringBuffer.append(item);
                                SPACE = 0;
                                while (SPACE < REMAINING_WIDTH) {// 右边空格
                                    stringBuffer.append(" ");
                                    SPACE+=7;
                                }
                            }else{
                                stringBuffer.append(item);
                            }
                        }
                        mRootView.getUsbThermalPrinter().addString(stringBuffer.toString());
                    }else{
                        mRootView.getUsbThermalPrinter().addString(recordPrintStyle.content);
                    }
                    mRootView.getUsbThermalPrinter().printString();
                }
                mRootView.getUsbThermalPrinter().walkPaper(10);

            } catch (Exception e) {
                e.printStackTrace();
                Result = e.toString();
                if (Result.equals("com.telpo.tps550.api.printer.NoPaperException")) {
                    nopaper = true;
                } else if (Result.equals("com.telpo.tps550.api.printer.OverHeatException")) {
                    handler.sendMessage(handler.obtainMessage(OVERHEAT, 1, 0, null));
                } else {
                    handler.sendMessage(handler.obtainMessage(PRINTERR, 1, 0, null));
                }
            } finally {
                handler.sendMessage(handler.obtainMessage(CANCELPROMPT, 1, 0, null));
                if (nopaper) {
                    handler.sendMessage(handler.obtainMessage(NOPAPER, 1, 0, null));
                    nopaper = false;
                    return;
                }
            }
        }
    }

    String[] portNum = new String[20];
    String[] productNum = new String[20];
    String[] readerNum = new String[4];

    private String getUsbPrinterDev(){
        String msgSuccess = ShellUtils.execCommand("cat /proc/bus/usb/devices", false).successMsg;
        searchAllIndex(msgSuccess,"Dev#=",1);
        searchAllIndex(msgSuccess,"Product=",2);
        return checkPort(portNum,productNum);
    }

    private void searchAllIndex(String str,String key,int type) {
        if(str != null && !str.equals("")){
            int a = str.indexOf(key);
            int i=-1;
            while (a != -1) {
                i++;
                if(type ==1) {
                    portNum[i] = str.substring(a+5, a+8);
                    LogUtils.debugInfo("idcard demo", "portNum["+i+"]:"+portNum[i]);
                }
                else if(type ==2) {
                    productNum[i] = str.substring(a+8, a+27);
                    LogUtils.debugInfo("idcard demo", "portNum["+i+"]:"+portNum[i]);
                }
                a = str.indexOf(key, a + 1);//*浠庤繖涓储寮曞線鍚庡紑濮嬬涓�涓嚭鐜扮殑浣嶇疆
            }
        }
    }

    private String checkPort(String[] port,String[] product) {
        int k = -1;
        for(int i=0;i<20;i++) {
            if(productNum[i] != null &&productNum[i].equals("USB Thermal Printer")) {
                k++;
                readerNum[k] = portNum[i];
                LogUtils.debugInfo("idcard demo", "readnum[]:"+readerNum[k]);
                editor.putString("usbPrinterDev", readerNum[k]);
                editor.commit();
                return readerNum[k];
            }
        }
        editor.putString("usbPrinterDev", "-2");
        editor.commit();
        return "-2";
    }

    @Inject
    public PrintPresenter(PrintContract.Model model, PrintContract.View rootView) {
        super(model, rootView);
    }

    public void init() {
        //获取手机型号
        mRootView.getTvTitle().setText("打印信息");
        mRootView.getTvCommit().setText("确定打印");
        LogUtils.debugInfo("zp","手机型号:::"+Build.MODEL);

        if(Build.MODEL.equals("K-Link V6")){
               return;
        }
        mParam.id = mRootView.getActivity().getIntent().getStringExtra(AppConst.ID);
        initView();
//        //真数据
        if(mParam.id==null||mParam.id.equals("0")){
//以下是设置假数据
            PropertyCharge.RecordDetail item = new PropertyCharge.RecordDetail();
            item.addr = "地址啊啊啊 啊";
            item.bname = "地址啊啊啊 啊";
            item.c_building_id = "地址啊啊啊 啊";
            item.c_collection_type = 1;
            item.c_corpid = "地址啊啊啊 啊";
            item.c_corpName = "地址啊啊啊 啊";
            item.c_fee_type_name = "地址啊啊啊 啊";
            item.c_last_time_num = "地址啊啊啊 啊";
            item.c_nodedate_id = "地址啊啊啊 啊";
            item.c_quantity= "地址啊啊啊 啊";
            item.c_price = 44;
            item.c_payment_no = "地址啊啊啊 啊";
            item.d_receipt_date = "地址啊啊啊 啊";
            item.countAmount = 55;
            item.c_payment_name= "地址啊啊啊 啊";
            mRecordDetailList.add(item);
            setData(mRecordDetailList.get(0));
            mAdapter.setIsDetailVisibility(isDetailVisibility);
            mAdapter.notifyDataSetChanged();
//        假数据结束
        }else {
            queryRecordDetail();
        }
        initListener();
    }

    private SharedPreferences preference;
    private SharedPreferences.Editor editor;
    /**
     * 初始化热敏打印需要的东西
     */
    private void initPrint() {
        Intent intent = new Intent(PRT_TAG);
        intent.setPackage(mRootView.getActivity().getPackageName());
        intent.setComponent(new ComponentName("com.print.service", "com.print.service.printservice"));

        preference = mRootView.getActivity().getSharedPreferences("TPS390PRINTER", mRootView.getActivity().MODE_PRIVATE);
        editor = preference.edit();

        usbPrinterDev = preference.getString("usbPrinterDev", "-1");

        handler = new MyHandler();

    }

    private void getVersion(){
        try {
            LogUtils.debugInfo("idcard demo", "getVersion");
//            mRootView.getUsbThermalPrinter().start(0);
            //mRootView.getUsbThermalPrinter().start(1);
            mRootView.getUsbThermalPrinter().reset();
            printVersion = mRootView.getUsbThermalPrinter().getVersion();
            LogUtils.debugInfo("idcard demo", "printVersion:"+printVersion);
        } catch (TelpoException e) {
            e.printStackTrace();
        } finally {
            if (printVersion != null) {
                Message message = new Message();
                message.what = PRINTVERSION;
                message.obj = "1";
                handler.sendMessage(message);
            } else {
                Message message = new Message();
                message.what = PRINTVERSION;
                message.obj = "0";
                handler.sendMessage(message);
            }
        }
    }

    private void initView() {
        mAdapter = new PaymentDetailViewAdapter(mRecordDetailList, new PaymentDetailViewAdapter.OnPaymentDetailListener() {
            @Override
            public void onClick(int mPosition) {
            }
        });
        mRootView.getListview().setAdapter(mAdapter);
        mRootView.getListview().setNestedScrollingEnabled(false);
        mRootView.getListview().setFocusable(false);
    }

    private void initListener() {
        //点击打印
        mRootView.getTvCommit().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(Build.MODEL.equals("V1s")){
                    setPrintUiV1s();//设置打印数据
                    AidlUtil.getInstance().connectPrinterService(mRootView.getActivity());
                    AidlUtil.getInstance().initPrinter();
                        for (int i = 0; i <2 ; i++) {
                            AidlUtil.getInstance().printText("\t\t\t\t\t\t\t\tXXX物业账单信息", 34, true, false);
                            AidlUtil.getInstance().printText(content.toString()+"\n\n\n\n\n", 24, false, false);
                        }
                }else {
                    initPrint();
                    getVersion();
                    onStart2();
                    checkPrint();
                    posPrint();
                }
            }
        });
    }

    private void setPrintUiV1s(){
        content = new StringBuffer();
        content.append("账单编号: " + mRecordDetail.c_payment_no);
        content.append("\n收款时间: " + mRecordDetail.d_receipt_date);
        content.append("\n住    址: " + mRecordDetail.addr);
        content.append("\n姓    名: " + mRecordDetail.c_payment_name);
        content.append("\n收 款 人: " + mRecordDetail.c_payee_name);
        content.append("\n收款方式: " + mCollectionType[mRecordDetail.c_collection_type]);
        content.append("\n-------------------------------");
        content.append("\n\t\t\t\t名称\t\t\t\t\t\t\t\t用量\t\t\t\t\t\t\t\t单价\t\t\t\t\t\t\t\t小计");
        content.append("\n\t\t\t\t"+mRecordDetail.c_fee_type_name+"\t\t\t\t\t\t\t\t"+mRecordDetail.c_quantity+"\t\t\t\t\t\t\t\t"+mRecordDetail.c_price+"\t\t\t\t\t\t\t\t"+mRecordDetail.countAmount);
        content.append("\n-------------------------------");
    }


    private void setPrintUi(){
        mRecordPrintStyleList.clear();
        content = new StringBuffer();
        content.append("账单编号: " + mRecordDetail.c_payment_no);
        content.append("\n收款时间: " + mRecordDetail.d_receipt_date);
        content.append("\n住    址: " + mRecordDetail.addr);
        content.append("\n姓    名: " + mRecordDetail.c_payment_name);
        content.append("\n收 款 人: " + mRecordDetail.c_payee_name);
        content.append("\n收款方式: " + mCollectionType[mRecordDetail.c_collection_type]);
        content1 = new StringBuffer();
        content1.append(content.toString());
        content.append("\n-------------------------------");
        content.append("\n\t\t\t\t名称\t\t\t\t\t\t\t\t用量\t\t\t\t\t\t\t\t单价\t\t\t\t\t\t\t\t小计");
        content.append("\n\t\t\t\t"+mRecordDetail.c_fee_type_name+"\t\t\t\t\t\t\t\t"+mRecordDetail.c_quantity+"\t\t\t\t\t\t\t\t"+mRecordDetail.c_price+"\t\t\t\t\t\t\t\t"+mRecordDetail.countAmount);
        content.append("\n-------------------------------");

        content1.append("\n---------------------------");
        content1.append("\n名称"+"\t\t\t"+"用量"+"\t\t\t"+"单价"+"\t\t\t"+"小计");
        content1.append("\n"+mRecordDetail.c_fee_type_name+"\t\t\t"+mRecordDetail.c_quantity+"\t\t\t"+mRecordDetail.c_price+"\t\t\t"+mRecordDetail.countAmount);
        content1.append("\n---------------------------");
        for (int i = 0; i <2 ; i++) {
            mRecordPrintStyleList.add(new PropertyCharge.RecordPrintStyle("XXX物业账单信息", 30, 4, true, 1, 0, 0, 10));
            mRecordPrintStyleList.add(new PropertyCharge.RecordPrintStyle(content1.toString()+"\n\n\n\n\n", 22, 2, false, 0, 0, 0, 0));
        }

//            mRecordPrintStyleList.add(new PropertyCharge.RecordPrintStyle("XXX物业账单信息", 30, 4, true, 1, 0, 0, 10));
//            mRecordPrintStyleList.add(new PropertyCharge.RecordPrintStyle("", 20, 1, false, 0, 0, 0, 5));
//            mRecordPrintStyleList.add(new PropertyCharge.RecordPrintStyle("编号: " + mRecordDetail.c_payment_no, 24, 2, false, 0, 0, 0, 0));
//            mRecordPrintStyleList.add(new PropertyCharge.RecordPrintStyle("时间: " + mRecordDetail.d_receipt_date, 24, 2, false, 0, 0, 0, 0));
//            mRecordPrintStyleList.add(new PropertyCharge.RecordPrintStyle("住址: " + mRecordDetail.addr, 24, 2, false, 0, 0, 0, 0));
//            mRecordPrintStyleList.add(new PropertyCharge.RecordPrintStyle("姓名: " + mRecordDetail.c_payment_name, 24, 2, false, 0, 0, 0, 0));
//            mRecordPrintStyleList.add(new PropertyCharge.RecordPrintStyle("收款人: " + mRecordDetail.c_payee_name, 24, 2, false, 0, 0, 0, 0));
//            mRecordPrintStyleList.add(new PropertyCharge.RecordPrintStyle("收款方式: " + mCollectionType[mRecordDetail.c_collection_type], 24, 2, false, 0, 0, 0, 0));
//
//            mRecordPrintStyleList.add(new PropertyCharge.RecordPrintStyle("-------------------------------", 20, 0, false, 1, 0, 0, 0));
//            mRecordPrintStyleList.add(new PropertyCharge.RecordPrintStyle("名称" + SEPARATOR + "用量" + SEPARATOR + "单价" + SEPARATOR + "小计", 22, 5, false, 0, 0, 0, 0));
//            mRecordPrintStyleList.add(new PropertyCharge.RecordPrintStyle("-------------------------------", 20, 0, false, 1, 0, 0, 0));
//
//            for (PropertyCharge.RecordDetail recordDetail : mRecordDetailList){
//                mRecordPrintStyleList.add(new PropertyCharge.RecordPrintStyle(recordDetail.c_fee_type_name, 22, 1, false, 0, 7, 0, 0));
//                mRecordPrintStyleList.add(new PropertyCharge.RecordPrintStyle(" " + SEPARATOR + recordDetail.c_quantity + SEPARATOR + TextViewUtils.getPrintPrice3(recordDetail.c_price) + SEPARATOR + TextViewUtils.getPrintPrice3(recordDetail.c_paid_amount), 20, 1, false, 0, 0, 0, 0));
//            }
//
//            mRecordPrintStyleList.add(new PropertyCharge.RecordPrintStyle("-------------------------------", 20, 1, false, 1, 0, 0, 0));
//            mRecordPrintStyleList.add(new PropertyCharge.RecordPrintStyle("合计: "+ TextViewUtils.getPrintPrice3(mRecordDetail.c_paid_amount) +"元", 24, 1, false, 2, 0, 0, 5));
//            mRecordPrintStyleList.add(new PropertyCharge.RecordPrintStyle("\n\n\n\n\n", 24, 1, false, 2, 0, 0, 5));
    }

    private List<PropertyCharge.RecordPrintStyle> mRecordPrintStyleList = new ArrayList<>();
    private String SEPARATOR = ",";// 分隔符
    private void posPrint() {

        if (LowBattery == true) {
            handler.sendMessage(handler.obtainMessage(LOWBATTERY, 1, 0, null));
        } else {
            if (!nopaper) {
                progressDialog = ProgressDialog.show(mRootView.getActivity(), getString(R.string.bl_dy),
                        getString(R.string.printing_wait));
                handler.sendMessage(handler.obtainMessage(PRINTCONTENT, 1, 0, null));
            } else {
                Toast.makeText(mApplication, getString(R.string.ptintInit), Toast.LENGTH_LONG)
                        .show();
            }
        }
    }

    /**
     * 获取数据
     */
    public void queryRecordDetail() {
        mModel.queryRecordDetail(mParam)
                .subscribeOn(Schedulers.io())
                .retryWhen(new RetryWithDelay(2, 2))//遇到错误时重试,第一个参数为重试几次,第二个参数为重试的间隔
                .doOnSubscribe(dismPosable -> {

                }).subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doFinally(() -> {

                })
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))//使用 Rxlifecycle,使 DismPosable 和 Activity 一起销毁
                .subscribe(new ErrorHandleSubscriber<BaseResponse<List<PropertyCharge.RecordDetail>>>(mErrorHandler) {
                    @Override
                    public void onNext(BaseResponse<List<PropertyCharge.RecordDetail>> response) {
                        if(response.getStatus().equals(BaseAppConst.OUT_TOKEN)){
                            MyApplication.getInstance().gotoLoginActivity();
                        }
                        if(!response.isSuccess()){
                            ArmsUtils.makeText(mApplication, response.getStatuMsg());
                            return;
                        }

                        mRecordDetailList.addAll(response.getData());

                        if (null != mRecordDetailList && mRecordDetailList.size() > 0) {
                            PropertyCharge.RecordDetail recordDetail = mRecordDetailList.get(0);
                            setData(recordDetail);
                            mAdapter.setIsDetailVisibility(isDetailVisibility);
                            mAdapter.notifyDataSetChanged();
                        }

                    }
                });
    }

    /**
     * 设置数据
     * @param recordDetail
     */
    private void setData(PropertyCharge.RecordDetail recordDetail){
        this.mRecordDetail = recordDetail;
        mRootView.getTvTotalPrice().setText(TextViewUtils.getPaymentDetailsPrice(recordDetail.c_paid_amount));
        mRootView.getTvNumber().setText(recordDetail.c_payment_no);
        mRootView.getTvData().setText(recordDetail.d_receipt_date);
        mRootView.getTvAddress().setText(recordDetail.addr);
        mRootView.getTvName().setText(recordDetail.c_payment_name);
        mRootView.getTvPayPeople().setText(recordDetail.c_payee_name);
        mRootView.getTvPayType().setText(mCollectionType[recordDetail.c_collection_type]);
        mRootView.getTvTotalPrice2().setText(TextViewUtils.getPaymentDetailsPrice2(recordDetail.c_paid_amount));
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;

        this.mParam = null;
        this.mRecordDetailList = null;
        this.mAdapter = null;
        this.mCollectionType = null;
        this.mRecordDetail = null;
    }

    public void finish(){
        if(isDetailVisibility){
            mRootView.getActivity().finish();
        }else{
            isDetailVisibility = true;
            mAdapter.setIsDetailVisibility(isDetailVisibility);
            mAdapter.notifyDataSetChanged();
            mRootView.getTvCommit().setText("确定打印");
        }
    }

    private void noPaperDlg() {
        AlertDialog.Builder dlg = new AlertDialog.Builder(mRootView.getActivity());
        dlg.setTitle(ArmsUtils.getString(mApplication, R.string.noPaper));
        dlg.setMessage(ArmsUtils.getString(mApplication, R.string.noPaperNotice));
        mRootView.getTvCommit().setEnabled(true);
        dlg.setCancelable(false);
        dlg.setPositiveButton(R.string.sure, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                ThermalPrinter.stop(mRootView.getActivity());
            }
        });
        dlg.show();
    }

    /**
     * 电池电量广播
     */
    private final BroadcastReceiver printReceive = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
                int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS,
                        BatteryManager.BATTERY_STATUS_NOT_CHARGING);
                int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
                int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 0);
                // TPS390 can not print,while in low battery,whether is charging or not charging
                if (SystemUtil.getDeviceType() == StringUtil.DeviceModelEnum.TPS390.ordinal()
                        || SystemUtil.getDeviceType() == StringUtil.DeviceModelEnum.TPS390A.ordinal()) {
                    if (level * 5 <= scale) {
                        LowBattery = true;
                    } else {
                        LowBattery = false;
                    }
                } else {
                    if (status != BatteryManager.BATTERY_STATUS_CHARGING) {
                        if (level * 5 <= scale) {
                            LowBattery = true;
                        } else {
                            LowBattery = false;
                        }
                    } else {
                        LowBattery = false;
                    }
                }
            }
            // Only use for TPS550MTK devices
            else if (action.equals("android.intent.action.BATTERY_CAPACITY_EVENT")) {
                int status = intent.getIntExtra("action", 0);
                int level = intent.getIntExtra("level", 0);
                if (status == 0) {
                    if (level < 1) {
                        LowBattery = true;
                    } else {
                        LowBattery = false;
                    }
                } else {
                    LowBattery = false;
                }
            }
        }
    };

    public String getString(int string){
        return ArmsUtils.getString(mApplication, string);
    }

}
